Dashboard Temp Share Shortlinks Frames API

HTMLify

SPARTA PROJECT.html
Views: 21 | Author: ciro107
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>SPARTA PROJECT</title>
<style>
:root{
  --bg:#0a0b0a;
  --panel:#121412;
  --panel2:#171917;
  --border:#262a26;
  --accent:#c6ff3c;
  --accent-dim:#8fce1c;
  --accent2:#6ff0c0;
  --text:#eef0ea;
  --text-dim:#8a8f88;
  --red:#ff4d4d;
  --radius:10px;
  box-sizing:border-box;
  padding-top:env(safe-area-inset-top,0px);
  padding-bottom:env(safe-area-inset-bottom,0px);
}
*{box-sizing:border-box;}
html{scroll-padding-top:env(safe-area-inset-top,0px);}
html,body{height:100%;}
body{
  margin:0;
  background:var(--bg);
  color:var(--text);
  font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
  -webkit-font-smoothing:antialiased;
  min-height:100%;
  padding-bottom:calc(72px + env(safe-area-inset-bottom,0px));
}
::selection{background:var(--accent);color:#0a0b0a;}
a{color:var(--accent);}

/* HEADER */
header.top{
  position:sticky;top:0;z-index:50;
  padding-top:calc(12px + env(safe-area-inset-top,0px));
  background:linear-gradient(180deg,rgba(10,11,10,.98),rgba(10,11,10,.9));
  backdrop-filter:blur(6px);
  border-bottom:1px solid var(--border);
  padding-left:16px;padding-right:16px;padding-bottom:10px;
  display:flex;align-items:center;justify-content:space-between;
}
.brand{display:flex;flex-direction:column;line-height:1.05;}
.brand .s1{font-size:11px;letter-spacing:.32em;color:var(--accent2);font-weight:600;}
.brand .s2{font-size:20px;letter-spacing:.06em;font-weight:800;color:var(--text);}
.brand .s2 span{color:var(--accent);}
.save-indicator{display:flex;align-items:center;gap:6px;font-size:11px;color:var(--text-dim);letter-spacing:.05em;}
.save-dot{width:8px;height:8px;border-radius:50%;background:var(--accent);box-shadow:0 0 8px var(--accent);}
.save-dot.saving{animation:pulse 1s ease-in-out;}
@keyframes pulse{0%{opacity:.3;transform:scale(.8);}50%{opacity:1;transform:scale(1.3);}100%{opacity:1;transform:scale(1);}}

main{max-width:760px;margin:0 auto;padding:16px;}
.panel{display:none;}
.panel.active{display:block;animation:fadein .18s ease;}
@keyframes fadein{from{opacity:0;transform:translateY(4px);}to{opacity:1;transform:translateY(0);}}

h2.section-title{
  font-size:12px;letter-spacing:.24em;text-transform:uppercase;color:var(--accent2);
  margin:22px 0 10px;font-weight:700;
}
h2.section-title:first-child{margin-top:0;}

.card{
  background:var(--panel);
  border:1px solid var(--border);
  border-radius:var(--radius);
  padding:14px;
}
.card + .card{margin-top:10px;}

.grid-stats{display:grid;grid-template-columns:repeat(2,1fr);gap:10px;}
.stat{
  background:var(--panel);
  border:1px solid var(--border);
  border-radius:var(--radius);
  padding:12px;
  display:flex;flex-direction:column;gap:4px;
}
.stat .label{font-size:10.5px;color:var(--text-dim);letter-spacing:.08em;text-transform:uppercase;}
.stat .value{font-size:22px;font-weight:800;color:var(--text);}
.stat .value .unit{font-size:12px;color:var(--text-dim);font-weight:500;margin-left:2px;}
.stat .value.accent{color:var(--accent);}
.stat .sub{font-size:11px;color:var(--text-dim);}
.stat .sub.up{color:var(--accent);}
.stat .sub.down{color:var(--red);}

.progress-wrap{margin-top:4px;}
.progress-bar-bg{
  width:100%;height:10px;border-radius:6px;background:#1c1f1c;overflow:hidden;border:1px solid var(--border);
}
.progress-bar-fill{
  height:100%;background:linear-gradient(90deg,var(--accent-dim),var(--accent));
  box-shadow:0 0 10px rgba(198,255,60,.5);
  border-radius:6px;transition:width .3s ease;
}
.progress-label{display:flex;justify-content:space-between;font-size:12px;color:var(--text-dim);margin-top:6px;}
.progress-label b{color:var(--text);}

/* FORMS */
label{display:block;font-size:11px;color:var(--text-dim);letter-spacing:.05em;text-transform:uppercase;margin:10px 0 4px;}
label:first-child{margin-top:0;}
input[type=date],input[type=number],input[type=text],select,textarea{
  width:100%;background:var(--panel2);border:1px solid var(--border);color:var(--text);
  border-radius:8px;padding:11px 12px;font-size:15px;font-family:inherit;
  -webkit-appearance:none;appearance:none;
}
input:focus,select:focus,textarea:focus{outline:none;border-color:var(--accent);}
textarea{resize:vertical;min-height:56px;}
input[type=range]{width:100%;accent-color:var(--accent);}
.range-row{display:flex;align-items:center;gap:10px;}
.range-row output{min-width:26px;text-align:center;font-weight:700;color:var(--accent);}

.field-row2{display:grid;grid-template-columns:1fr 1fr;gap:10px;}
.field-row3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;}

button{
  font-family:inherit;cursor:pointer;border:none;
}
.btn{
  display:inline-flex;align-items:center;justify-content:center;gap:6px;
  background:var(--accent);color:#0a0b0a;font-weight:800;letter-spacing:.04em;
  padding:13px 18px;border-radius:8px;font-size:14px;width:100%;
  text-transform:uppercase;
}
.btn:active{transform:scale(.98);}
.btn.secondary{background:transparent;color:var(--text);border:1px solid var(--border);}
.btn.ghost{background:transparent;color:var(--accent2);border:1px solid var(--accent2);}
.btn.danger{background:transparent;color:var(--red);border:1px solid var(--red);}
.btn.small{width:auto;padding:8px 12px;font-size:12px;}
.btn-row{display:flex;gap:8px;margin-top:10px;flex-wrap:wrap;}
.btn-row .btn{width:auto;flex:1;}

/* NAV */
nav.bottom{
  position:fixed;left:0;right:0;bottom:0;z-index:50;
  background:rgba(15,17,15,.97);backdrop-filter:blur(8px);
  border-top:1px solid var(--border);
  display:flex;
  padding-bottom:env(safe-area-inset-bottom,0px);
}
nav.bottom button{
  flex:1;background:none;color:var(--text-dim);padding:9px 2px 8px;
  display:flex;flex-direction:column;align-items:center;gap:3px;font-size:10px;letter-spacing:.04em;
  text-transform:uppercase;font-weight:600;
}
nav.bottom button .ic{font-size:18px;line-height:1;}
nav.bottom button.active{color:var(--accent);}
nav.bottom button.active .ic{filter:drop-shadow(0 0 6px rgba(198,255,60,.7));}

/* WORKOUT PICKER */
.wo-picker{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;}
.wo-pick-btn{
  background:var(--panel2);border:1px solid var(--border);border-radius:8px;
  padding:14px 6px;color:var(--text-dim);font-weight:800;font-size:15px;text-align:center;
}
.wo-pick-btn small{display:block;font-size:9.5px;font-weight:500;color:var(--text-dim);margin-top:3px;text-transform:none;letter-spacing:0;}
.wo-pick-btn.active{border-color:var(--accent);color:var(--accent);box-shadow:0 0 0 1px var(--accent) inset;}

.ex-card{border:1px solid var(--border);border-radius:var(--radius);background:var(--panel);padding:13px;margin-top:10px;}
.ex-card .ex-head{display:flex;justify-content:space-between;align-items:flex-start;gap:8px;}
.ex-card .ex-name{font-size:15px;font-weight:800;color:var(--text);}
.ex-card .ex-target{font-size:11.5px;color:var(--text-dim);margin-top:2px;}
.tag{
  display:inline-block;font-size:9.5px;letter-spacing:.06em;text-transform:uppercase;
  padding:3px 7px;border-radius:5px;font-weight:700;
}
.tag.planned{background:#1c2a17;color:var(--accent2);border:1px solid #294024;}
.tag.executed{background:#1e230f;color:var(--accent);border:1px solid #35400f;}
.tag.pr{background:#2a1414;color:var(--red);border:1px solid #4a1e1e;}
.last-perf{
  margin-top:8px;font-size:12px;color:var(--text-dim);background:var(--panel2);
  border:1px solid var(--border);border-radius:7px;padding:8px 10px;
}
.progression-note{
  margin-top:6px;font-size:12.5px;font-weight:700;border-radius:7px;padding:8px 10px;
}
.progression-note.up{background:rgba(198,255,60,.08);color:var(--accent);border:1px solid rgba(198,255,60,.35);}
.progression-note.hold{background:rgba(111,240,192,.06);color:var(--accent2);border:1px solid rgba(111,240,192,.3);}

.sets-table{width:100%;border-collapse:collapse;margin-top:10px;}
.sets-table th{font-size:10px;color:var(--text-dim);text-transform:uppercase;letter-spacing:.04em;text-align:center;padding-bottom:5px;font-weight:600;}
.sets-table td{padding:3px;}
.sets-table td input{text-align:center;padding:9px 4px;font-size:14px;}
.sets-table td.set-label{font-size:11px;color:var(--text-dim);text-align:center;width:34px;font-weight:700;}

/* TABLES (history/progress) */
.table-scroll{overflow-x:auto;-webkit-overflow-scrolling:touch;margin-top:8px;border-radius:var(--radius);border:1px solid var(--border);}
table.data{width:100%;border-collapse:collapse;min-width:560px;background:var(--panel);}
table.data th{
  background:var(--panel2);color:var(--text-dim);font-size:10.5px;text-transform:uppercase;letter-spacing:.04em;
  text-align:left;padding:9px 10px;white-space:nowrap;border-bottom:1px solid var(--border);
}
table.data td{padding:9px 10px;font-size:13px;border-bottom:1px solid var(--border);white-space:nowrap;color:var(--text);}
table.data tr:last-child td{border-bottom:none;}
table.data td.num{font-variant-numeric:tabular-nums;}
.pain-badge{padding:2px 7px;border-radius:5px;font-size:11px;font-weight:700;}
.del-btn{background:none;color:var(--red);font-size:16px;padding:2px 6px;}

.chart-wrap{margin-top:6px;}
canvas.chart{width:100%;height:180px;display:block;}
.empty-note{color:var(--text-dim);font-size:12.5px;padding:14px 4px;text-align:center;}

.checkin-inline{display:grid;grid-template-columns:1fr 1fr;gap:10px;}

.settings-block{margin-top:6px;}
.settings-desc{font-size:12px;color:var(--text-dim);margin-top:4px;margin-bottom:8px;line-height:1.4;}

.modal-overlay{
  position:fixed;inset:0;background:rgba(0,0,0,.7);z-index:100;
  display:none;align-items:center;justify-content:center;padding:20px;
}
.modal-overlay.active{display:flex;}
.modal-box{
  background:var(--panel);border:1px solid var(--border);border-radius:var(--radius);
  padding:20px;max-width:340px;width:100%;
}
.modal-box h3{margin:0 0 8px;font-size:16px;color:var(--red);}
.modal-box p{font-size:13px;color:var(--text-dim);line-height:1.5;margin-bottom:16px;}

.toast{
  position:fixed;bottom:calc(84px + env(safe-area-inset-bottom,0px));left:50%;transform:translateX(-50%);
  background:var(--accent);color:#0a0b0a;font-weight:700;font-size:13px;
  padding:10px 16px;border-radius:8px;z-index:200;opacity:0;pointer-events:none;transition:opacity .25s,transform .25s;
  white-space:nowrap;
}
.toast.show{opacity:1;transform:translateX(-50%) translateY(-4px);}

.hint{font-size:11.5px;color:var(--text-dim);margin-top:6px;line-height:1.4;}
.divider{height:1px;background:var(--border);margin:14px 0;}
.week-bars{display:flex;align-items:flex-end;gap:6px;height:90px;margin-top:10px;}
.week-bar-col{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:flex-end;height:100%;gap:4px;}
.week-bar{width:100%;background:linear-gradient(180deg,var(--accent),var(--accent-dim));border-radius:4px 4px 0 0;min-height:2px;}
.week-bar-lbl{font-size:9.5px;color:var(--text-dim);}
</style>
</head>
<body>

<header class="top">
  <div class="brand">
    <span class="s1">FITNESS CONTROL COCKPIT</span>
    <span class="s2">SPARTA <span>PROJECT</span></span>
  </div>
  <div class="save-indicator"><span class="save-dot" id="saveDot"></span><span id="saveText">AUTO-SAVE</span></div>
</header>

<main>

  <!-- ============ COCKPIT ============ -->
  <section class="panel active" id="panel-cockpit">
    <h2 class="section-title">Stato Missione</h2>
    <div class="card">
      <div class="progress-label"><span>Workout completati</span><b id="ck-wcount">0 / 24</b></div>
      <div class="progress-bar-bg"><div class="progress-bar-fill" id="ck-wbar" style="width:0%"></div></div>
      <div class="progress-label" style="margin-top:8px;"><span>Aderenza programma</span><b id="ck-adherence">0%</b></div>
    </div>

    <div class="grid-stats" style="margin-top:10px;">
      <div class="stat"><div class="label">Settimana</div><div class="value accent" id="ck-week">— / 8</div></div>
      <div class="stat"><div class="label">Workouts / week</div><div class="value" id="ck-wpw">0</div></div>
      <div class="stat"><div class="label">Peso attuale</div><div class="value" id="ck-weight">—</div><div class="sub" id="ck-weight-delta"></div></div>
      <div class="stat"><div class="label">Vita attuale</div><div class="value" id="ck-waist">—</div><div class="sub" id="ck-waist-delta"></div></div>
      <div class="stat"><div class="label">Pull-up PR</div><div class="value accent" id="ck-pullup">0</div><div class="sub">reps libere / set</div></div>
      <div class="stat"><div class="label">HIIT completati</div><div class="value" id="ck-hiit">0</div></div>
      <div class="stat"><div class="label">Volume totale</div><div class="value" id="ck-volume">0<span class="unit">kg</span></div></div>
      <div class="stat"><div class="label">Durata media</div><div class="value" id="ck-avgdur">0<span class="unit">min</span></div></div>
    </div>

    <h2 class="section-title">Check-in Corporeo</h2>
    <div class="card">
      <label>Data</label>
      <input type="date" id="ci-date">
      <div class="checkin-inline">
        <div><label>Peso (kg)</label><input type="number" step="0.1" id="ci-weight" placeholder="es. 78.4"></div>
        <div><label>Vita (cm)</label><input type="number" step="0.1" id="ci-waist" placeholder="es. 86"></div>
      </div>
      <div class="checkin-inline">
        <div><label>Ore di sonno</label><input type="number" step="0.5" id="ci-sleep" placeholder="es. 7"></div>
        <div><label>Energia (1–10)</label><input type="number" min="1" max="10" id="ci-energy" placeholder="es. 7"></div>
      </div>
      <div class="btn-row"><button class="btn" id="btn-save-checkin">Salva check-in</button></div>
      <div class="hint">Puoi compilare solo i campi che vuoi: nessun campo è obbligatorio, tranne la data.</div>
    </div>
  </section>

  <!-- ============ WORKOUT ============ -->
  <section class="panel" id="panel-workout">
    <h2 class="section-title">Seleziona Workout</h2>
    <div class="card">
      <div class="wo-picker">
        <button class="wo-pick-btn" data-wo="A">A<small>Spalle+PC</small></button>
        <button class="wo-pick-btn" data-wo="B">B<small>Schiena+Glutei</small></button>
        <button class="wo-pick-btn" data-wo="C">C<small>Arms+Upper</small></button>
      </div>
      <label>Data sessione</label>
      <input type="date" id="wo-date">
    </div>

    <div id="wo-exercises"></div>

    <div id="wo-session-fields" style="display:none;">
      <h2 class="section-title">Dati Sessione</h2>
      <div class="card">
        <div class="field-row2">
          <div><label>Durata totale (min)</label><input type="number" id="wo-duration" placeholder="es. 55"></div>
          <div>
            <label>HIIT completato</label>
            <select id="wo-hiit"><option value="si">Sì</option><option value="no">No</option></select>
          </div>
        </div>
        <label>Dolore / disagio (0–10)</label>
        <div class="range-row"><input type="range" min="0" max="10" value="0" id="wo-pain"><output id="wo-pain-out">0</output></div>
        <label>Energia (1–10)</label>
        <div class="range-row"><input type="range" min="1" max="10" value="5" id="wo-energy"><output id="wo-energy-out">5</output></div>
        <label>Note</label>
        <textarea id="wo-notes" placeholder="Note libere sulla sessione..."></textarea>
        <div class="btn-row"><button class="btn" id="btn-save-workout">Salva workout</button></div>
      </div>
    </div>
  </section>

  <!-- ============ PROGRESS ============ -->
  <section class="panel" id="panel-progress">
    <h2 class="section-title">Peso</h2>
    <div class="card chart-wrap"><canvas class="chart" id="chart-weight"></canvas></div>

    <h2 class="section-title">Vita</h2>
    <div class="card chart-wrap"><canvas class="chart" id="chart-waist"></canvas></div>

    <h2 class="section-title">Pull-up (max reps libere)</h2>
    <div class="card chart-wrap"><canvas class="chart" id="chart-pullup"></canvas></div>

    <h2 class="section-title">Volume per sessione</h2>
    <div class="card chart-wrap"><canvas class="chart" id="chart-volume"></canvas></div>

    <h2 class="section-title">Carichi Principali</h2>
    <div class="card">
      <div class="table-scroll">
        <table class="data" id="tbl-loads">
          <thead><tr><th>Esercizio</th><th>Miglior carico</th><th>Data</th></tr></thead>
          <tbody></tbody>
        </table>
      </div>
    </div>

    <h2 class="section-title">Workouts per Settimana</h2>
    <div class="card">
      <div class="week-bars" id="week-bars"></div>
    </div>
  </section>

  <!-- ============ HISTORY ============ -->
  <section class="panel" id="panel-history">
    <h2 class="section-title">Storico Sessioni</h2>
    <div class="card">
      <div class="table-scroll">
        <table class="data" id="tbl-history">
          <thead><tr><th>Data</th><th>WO</th><th>Durata</th><th>Volume</th><th>HIIT</th><th>Dolore</th><th>Note</th><th></th></tr></thead>
          <tbody></tbody>
        </table>
      </div>
      <div class="empty-note" id="history-empty" style="display:none;">Nessuna sessione registrata.</div>
    </div>

    <h2 class="section-title">Storico Check-in</h2>
    <div class="card">
      <div class="table-scroll">
        <table class="data" id="tbl-checkins">
          <thead><tr><th>Data</th><th>Peso</th><th>Vita</th><th>Sonno</th><th>Energia</th><th></th></tr></thead>
          <tbody></tbody>
        </table>
      </div>
      <div class="empty-note" id="checkins-empty" style="display:none;">Nessun check-in registrato.</div>
    </div>
  </section>

  <!-- ============ SETTINGS ============ -->
  <section class="panel" id="panel-settings">
    <h2 class="section-title">Programma</h2>
    <div class="card settings-block">
      <label>Data inizio programma (Settimana 1 / Giorno 1)</label>
      <input type="date" id="set-startdate">
      <div class="btn-row"><button class="btn secondary" id="btn-save-startdate">Salva data inizio</button></div>
      <div class="hint">Determina il calcolo automatico di "Settimana corrente / 8" nel Cockpit.</div>
    </div>

    <h2 class="section-title">Backup Dati</h2>
    <div class="card settings-block">
      <div class="settings-desc">I dati sono salvati solo in locale su questo dispositivo/browser (localStorage). Esporta un backup regolarmente, soprattutto prima di cambiare browser o dispositivo.</div>
      <div class="btn-row">
        <button class="btn ghost" id="btn-export-json">Esporta JSON</button>
      </div>
      <label style="margin-top:14px;">Importa JSON</label>
      <input type="file" id="input-import-json" accept="application/json">
      <div class="hint">Selezionando un file di backup precedentemente esportato, i dati verranno ripristinati (sovrascrivendo quelli attuali).</div>
    </div>

    <h2 class="section-title">Export CSV</h2>
    <div class="card settings-block">
      <div class="settings-desc">Esporta un CSV con tutti i dati di allenamento e check-in, utile per analisi esterne (Excel, Numbers, Sheets).</div>
      <div class="btn-row"><button class="btn ghost" id="btn-export-csv">Esporta CSV</button></div>
    </div>

    <h2 class="section-title">Zona Pericolosa</h2>
    <div class="card settings-block">
      <div class="settings-desc">Cancella permanentemente tutti i workout, check-in e impostazioni salvati su questo dispositivo.</div>
      <div class="btn-row"><button class="btn danger" id="btn-reset">Reset dati</button></div>
    </div>

    <div class="hint" style="text-align:center;margin-top:20px;opacity:.5;">SPARTA PROJECT · 8 settimane · standalone offline app</div>
  </section>

</main>

<nav class="bottom">
  <button class="nav-btn active" data-tab="cockpit"><span class="ic">⌂</span>Cockpit</button>
  <button class="nav-btn" data-tab="workout"><span class="ic">⚡</span>Workout</button>
  <button class="nav-btn" data-tab="progress"><span class="ic">📈</span>Progress</button>
  <button class="nav-btn" data-tab="history"><span class="ic">☰</span>History</button>
  <button class="nav-btn" data-tab="settings"><span class="ic">⚙</span>Settings</button>
</nav>

<div class="modal-overlay" id="reset-modal">
  <div class="modal-box">
    <h3>Confermi il reset?</h3>
    <p>Questa azione cancellerà definitivamente tutti i workout, check-in e impostazioni salvati. Non è reversibile. Ti consigliamo di esportare prima un backup JSON.</p>
    <div class="btn-row">
      <button class="btn secondary" id="reset-cancel">Annulla</button>
      <button class="btn danger" id="reset-confirm">Elimina tutto</button>
    </div>
  </div>
</div>

<div class="toast" id="toast"></div>

<script>
(function(){
"use strict";

/* ===================== PROGRAM DEFINITION ===================== */
const PROGRAM = {
  A: { name:"Workout A — Spalle + Posterior Chain", exercises:[
    {id:'A1', name:'Military Press', sets:3, repsMin:6, repsMax:10, rir:'1–2', rest:'~120 sec', alts:['Shoulder Press machine','Shoulder Press manubri']},
    {id:'A2', name:'Romanian Deadlift', sets:3, repsMin:8, repsMax:10, rir:'2', rest:'~120 sec', alts:['Romanian DB Deadlift','Hip Thrust']},
    {id:'A3', name:'Chest Press', sets:3, repsMin:8, repsMax:12, rir:'1–2', rest:'~90 sec', alts:['Incline DB Bench','Incline Chest Press']},
    {id:'A4', name:'Assisted Pull-ups / eccentriche', sets:4, repsMin:3, repsMax:5, rir:'~2', rest:'90–120 sec', alts:['Lat Machine presa neutra','Pull-up con elastico'], pullup:'assisted'},
    {id:'A5', name:'Alzate laterali', sets:3, repsMin:12, repsMax:15, rir:'1–2', rest:'60 sec', alts:['Cable Lateral Raise','Reverse Fly Machine']},
    {id:'A6', name:'Curl', sets:2, repsMin:10, repsMax:12, rir:'1–2', rest:'60 sec', alts:['Curl manubri alternati','Curl EZ']},
  ], hiit:true},
  B: { name:"Workout B — Schiena + Glutei/Hamstring", exercises:[
    {id:'B1', name:'Pull-up libero', sets:3, repsMin:1, repsMax:2, rir:'1–2', rest:'~120 sec', alts:['Lat Machine neutra','Assisted Pull-up'], pullup:'free'},
    {id:'B2', name:'Australian Pull-up', sets:3, repsMin:8, repsMax:12, rir:'1–2', rest:'90 sec', alts:['Low Cable Row','Machine Row']},
    {id:'B3', name:'Leg Curl', sets:3, repsMin:10, repsMax:15, rir:'1–2', rest:'75 sec', alts:['Seated Leg Curl','Lying Leg Curl']},
    {id:'B4', name:'Hip Thrust / Glute Machine', sets:3, repsMin:8, repsMax:12, rir:'1–2', rest:'90 sec', alts:['Glute Bridge','Cable Pull-through']},
    {id:'B5', name:'Leg Press controllata', sets:3, repsMin:10, repsMax:12, rir:'2–3', rest:'90–120 sec', alts:['Low Step-up','Box Squat controllato']},
    {id:'B6', name:'Curl EZ', sets:3, repsMin:8, repsMax:12, rir:'1–2', rest:'75 sec', alts:['Curl manubri','Preacher Machine Curl']},
  ], hiit:true},
  C: { name:"Workout C — Arms + Upper", exercises:[
    {id:'C1', name:'Incline DB Bench', sets:3, repsMin:8, repsMax:12, rir:'1–2', rest:'90 sec', alts:['Chest Press','Flat DB Bench']},
    {id:'C2', name:'Cable Lateral Raise', sets:3, repsMin:12, repsMax:15, rir:'1–2', rest:'60 sec', alts:['Alzate laterali manubri','Lateral Raise Machine']},
    {id:'C3', name:'Lat Machine', sets:3, repsMin:8, repsMax:12, rir:'1–2', rest:'90 sec', alts:['Neutral Pulldown','Assisted Pull-up']},
    {id:'C4', name:'Leg Curl', sets:3, repsMin:10, repsMax:15, rir:'1–2', rest:'75 sec', alts:['Seated Leg Curl','Assisted Nordic Curl']},
    {id:'C5', name:'Curl EZ', sets:3, repsMin:8, repsMax:12, rir:'1–2', rest:'75 sec', alts:['Incline DB Curl','Cable Curl']},
    {id:'C6', name:'Triceps Pushdown', sets:3, repsMin:10, repsMax:15, rir:'1–2', rest:'60–75 sec', alts:['Cable French Press','Overhead Cable Extension']},
    {id:'C7', name:'Calf Raise', sets:3, repsMin:12, repsMax:20, rir:'1–2', rest:'60 sec', alts:['Calf Raise on Leg Press','Seated Calf Raise']},
  ], hiit:true},
};
const NUM_SETS_UI = 4; // sempre 4 set predisposti per sicurezza
const TOTAL_TARGET_WORKOUTS = 24;
const TOTAL_WEEKS = 8;

/* ===================== STORAGE ===================== */
const STORAGE_KEY = 'sparta_project_data_v1';

function defaultData(){
  return { settings:{ startDate:null }, workouts:[], checkins:[] };
}
let DATA = loadData();

function loadData(){
  try{
    const raw = localStorage.getItem(STORAGE_KEY);
    if(!raw) return defaultData();
    const parsed = JSON.parse(raw);
    if(!parsed.settings) parsed.settings = {startDate:null};
    if(!parsed.workouts) parsed.workouts = [];
    if(!parsed.checkins) parsed.checkins = [];
    return parsed;
  }catch(e){
    console.error('Errore caricamento dati', e);
    return defaultData();
  }
}

let saveTimer=null;
function saveData(){
  try{
    localStorage.setItem(STORAGE_KEY, JSON.stringify(DATA));
    flashSaved();
  }catch(e){
    console.error('Errore salvataggio', e);
    showToast('Errore di salvataggio locale');
  }
}
function flashSaved(){
  const dot = document.getElementById('saveDot');
  const txt = document.getElementById('saveText');
  txt.textContent = 'SAVED';
  dot.classList.add('saving');
  clearTimeout(saveTimer);
  saveTimer = setTimeout(()=>{
    txt.textContent='AUTO-SAVE';
    dot.classList.remove('saving');
  }, 900);
}

/* ===================== UTIL ===================== */
function uid(){ return 'id'+Date.now().toString(36)+Math.random().toString(36).slice(2,8); }
function todayISO(){ const d=new Date(); return d.toISOString().slice(0,10); }
function fmtDate(iso){
  if(!iso) return '—';
  const [y,m,d]=iso.split('-');
  return `${d}/${m}/${y}`;
}
function num(v){ const n=parseFloat(v); return isNaN(n)?null:n; }
function showToast(msg){
  const t=document.getElementById('toast');
  t.textContent=msg;
  t.classList.add('show');
  clearTimeout(showToast._t);
  showToast._t=setTimeout(()=>t.classList.remove('show'),2200);
}

/* ===================== NAV ===================== */
document.querySelectorAll('nav.bottom .nav-btn').forEach(btn=>{
  btn.addEventListener('click', ()=>{
    document.querySelectorAll('nav.bottom .nav-btn').forEach(b=>b.classList.remove('active'));
    document.querySelectorAll('.panel').forEach(p=>p.classList.remove('active'));
    btn.classList.add('active');
    document.getElementById('panel-'+btn.dataset.tab).classList.add('active');
    window.scrollTo({top:0,behavior:'instant'});
    if(btn.dataset.tab==='progress') renderProgress();
    if(btn.dataset.tab==='history') renderHistory();
    if(btn.dataset.tab==='cockpit') renderCockpit();
  });
});

/* ===================== COCKPIT ===================== */
function computeCurrentWeek(){
  const sd = DATA.settings.startDate;
  if(!sd) return null;
  const start = new Date(sd+'T00:00:00');
  const now = new Date();
  const diffDays = Math.floor((now-start)/86400000);
  if(diffDays<0) return 0;
  return Math.min(TOTAL_WEEKS, Math.floor(diffDays/7)+1);
}

function allSets(workout, ex){ return ex.sets.filter(s=>s.reps!=null); }

function sessionVolume(w){
  let vol=0;
  w.exercises.forEach(ex=>{
    ex.sets.forEach(s=>{
      if(s.kg!=null && s.reps!=null) vol += s.kg*s.reps;
    });
  });
  return vol;
}

function pullupPR(){
  let pr=0;
  DATA.workouts.forEach(w=>{
    w.exercises.forEach(ex=>{
      if(ex.pullupType==='free'){
        ex.sets.forEach(s=>{ if(s.reps!=null && s.reps>pr) pr=s.reps; });
      }
    });
  });
  return pr;
}

function renderCockpit(){
  const wcount = DATA.workouts.length;
  document.getElementById('ck-wcount').textContent = `${wcount} / ${TOTAL_TARGET_WORKOUTS}`;
  const pct = Math.min(100, (wcount/TOTAL_TARGET_WORKOUTS)*100);
  document.getElementById('ck-wbar').style.width = pct+'%';
  document.getElementById('ck-adherence').textContent = pct.toFixed(1)+'%';

  const wk = computeCurrentWeek();
  document.getElementById('ck-week').textContent = wk==null ? '— / 8 (imposta data in Settings)' : `${wk} / ${TOTAL_WEEKS}`;

  const curWeek = wk || 1;
  const wpw = weeksCount()[curWeek-1] || 0;
  document.getElementById('ck-wpw').textContent = wpw;

  // checkins sorted
  const sortedCI = [...DATA.checkins].sort((a,b)=>a.date.localeCompare(b.date));
  const lastCI = sortedCI[sortedCI.length-1];
  const prevCI = sortedCI[sortedCI.length-2];
  const wEl = document.getElementById('ck-weight'), wDelta = document.getElementById('ck-weight-delta');
  const waEl = document.getElementById('ck-waist'), waDelta = document.getElementById('ck-waist-delta');
  if(lastCI && lastCI.weight!=null){
    wEl.innerHTML = lastCI.weight.toFixed(1)+'<span class="unit">kg</span>';
    if(prevCI && prevCI.weight!=null){
      const d = (lastCI.weight-prevCI.weight);
      wDelta.textContent = (d>=0?'+':'')+d.toFixed(1)+' kg vs precedente';
      wDelta.className='sub '+(d<0?'down':(d>0?'up':''));
    } else wDelta.textContent='';
  } else { wEl.textContent='—'; wDelta.textContent=''; }
  if(lastCI && lastCI.waist!=null){
    waEl.innerHTML = lastCI.waist.toFixed(1)+'<span class="unit">cm</span>';
    if(prevCI && prevCI.waist!=null){
      const d=(lastCI.waist-prevCI.waist);
      waDelta.textContent=(d>=0?'+':'')+d.toFixed(1)+' cm vs precedente';
      waDelta.className='sub '+(d<0?'up':(d>0?'down':''));
    } else waDelta.textContent='';
  } else { waEl.textContent='—'; waDelta.textContent=''; }

  document.getElementById('ck-pullup').textContent = pullupPR();
  document.getElementById('ck-hiit').textContent = DATA.workouts.filter(w=>w.hiit==='si').length;

  let totalVol=0, totalDur=0, durCount=0;
  DATA.workouts.forEach(w=>{
    totalVol += sessionVolume(w);
    if(w.duration!=null){ totalDur+=w.duration; durCount++; }
  });
  document.getElementById('ck-volume').innerHTML = Math.round(totalVol).toLocaleString('it-IT')+'<span class="unit">kg</span>';
  document.getElementById('ck-avgdur').innerHTML = (durCount? Math.round(totalDur/durCount):0)+'<span class="unit">min</span>';

  if(!document.getElementById('ci-date').value) document.getElementById('ci-date').value = todayISO();
}

function weeksCount(){
  const arr = new Array(TOTAL_WEEKS).fill(0);
  const sd = DATA.settings.startDate;
  if(!sd) return arr;
  const start = new Date(sd+'T00:00:00');
  DATA.workouts.forEach(w=>{
    const d = new Date(w.date+'T00:00:00');
    const diffDays = Math.floor((d-start)/86400000);
    if(diffDays>=0){
      const wk = Math.floor(diffDays/7)+1;
      if(wk>=1 && wk<=TOTAL_WEEKS) arr[wk-1]++;
    }
  });
  return arr;
}

document.getElementById('btn-save-checkin').addEventListener('click', ()=>{
  const date = document.getElementById('ci-date').value || todayISO();
  const weight = num(document.getElementById('ci-weight').value);
  const waist = num(document.getElementById('ci-waist').value);
  const sleep = num(document.getElementById('ci-sleep').value);
  const energy = num(document.getElementById('ci-energy').value);
  if(weight==null && waist==null && sleep==null && energy==null){
    showToast('Inserisci almeno un valore');
    return;
  }
  DATA.checkins.push({id:uid(), date, weight, waist, sleep, energy});
  saveData();
  document.getElementById('ci-weight').value='';
  document.getElementById('ci-waist').value='';
  document.getElementById('ci-sleep').value='';
  document.getElementById('ci-energy').value='';
  showToast('Check-in salvato');
  renderCockpit();
});

/* ===================== WORKOUT LOGGING ===================== */
let currentWO = null; // 'A'/'B'/'C'
document.getElementById('wo-date').value = todayISO();

document.querySelectorAll('.wo-pick-btn').forEach(btn=>{
  btn.addEventListener('click', ()=>{
    document.querySelectorAll('.wo-pick-btn').forEach(b=>b.classList.remove('active'));
    btn.classList.add('active');
    currentWO = btn.dataset.wo;
    renderWorkoutForm();
  });
});

function lastPerformanceFor(exId){
  // most recent workout (by date, fallback insertion order) containing this exercise
  const matches = DATA.workouts
    .filter(w=>w.exercises.some(e=>e.exId===exId))
    .sort((a,b)=> a.date.localeCompare(b.date));
  if(!matches.length) return null;
  const w = matches[matches.length-1];
  const ex = w.exercises.find(e=>e.exId===exId);
  return {date:w.date, ex};
}

function renderWorkoutForm(){
  const wrap = document.getElementById('wo-exercises');
  wrap.innerHTML='';
  if(!currentWO){ document.getElementById('wo-session-fields').style.display='none'; return; }
  const prog = PROGRAM[currentWO];
  const title = document.createElement('h2');
  title.className='section-title';
  title.textContent = prog.name;
  wrap.appendChild(title);

  prog.exercises.forEach(ex=>{
    const card = document.createElement('div');
    card.className='ex-card';
    card.dataset.exid = ex.id;

    const last = lastPerformanceFor(ex.id);
    let lastHtml='';
    let progressionHtml='';
    if(last){
      const setsStr = last.ex.sets.filter(s=>s.reps!=null).map(s=> (s.reps!=null? s.reps + (s.kg!=null? '@'+s.kg+'kg':'') : null)).filter(Boolean).join(' / ');
      lastHtml = `<div class="last-perf">Ultima prestazione (${fmtDate(last.date)}): <b>${last.ex.executedName}</b> — ${setsStr || 'nessun dato reps'}</div>`;
      const filledSets = last.ex.sets.filter(s=>s.reps!=null);
      if(filledSets.length){
        const allTop = filledSets.every(s=> s.reps >= ex.repsMax);
        if(allTop){
          progressionHtml = `<div class="progression-note up">⬆ PROGRESSIONE DISPONIBILE — Hai raggiunto il top del range (${ex.repsMax} reps) in tutti i set. Valuta un piccolo aumento del carico nella prossima sessione.</div>`;
        } else {
          progressionHtml = `<div class="progression-note hold">↔ Mantieni il carico attuale e prova a migliorare le reps verso il top del range (${ex.repsMin}–${ex.repsMax}).</div>`;
        }
      }
    }

    let altOptions = `<option value="${escapeHtml(ex.name)}">${escapeHtml(ex.name)} (programmato)</option>`;
    ex.alts.forEach(a=> altOptions += `<option value="${escapeHtml(a)}">${escapeHtml(a)}</option>`);
    altOptions += `<option value="__custom__">Altro (scrivi manualmente)...</option>`;

    let setsRows='';
    for(let i=1;i<=NUM_SETS_UI;i++){
      setsRows += `<tr>
        <td class="set-label">S${i}</td>
        <td><input type="number" step="0.5" placeholder="kg" data-role="kg" data-set="${i}"></td>
        <td><input type="number" step="1" placeholder="RIR" data-role="rir" data-set="${i}"></td>
        <td><input type="number" step="1" placeholder="reps" data-role="reps" data-set="${i}"></td>
      </tr>`;
    }

    card.innerHTML = `
      <div class="ex-head">
        <div>
          <div class="ex-name">${escapeHtml(ex.name)}</div>
          <div class="ex-target">${ex.sets}×${ex.repsMin}–${ex.repsMax} · RIR ${ex.rir} · rec. ${ex.rest}</div>
        </div>
        ${ex.pullup ? `<span class="tag pr">${ex.pullup==='free'?'PULL-UP':'ASSISTITO'}</span>`:''}
      </div>
      <span class="tag planned" style="margin-top:8px;display:inline-block;">Programmato: ${escapeHtml(ex.name)}</span>
      ${lastHtml}
      ${progressionHtml}
      <label style="margin-top:10px;">Esercizio realmente eseguito</label>
      <select data-role="exselect">${altOptions}</select>
      <input type="text" data-role="excustom" placeholder="Nome esercizio eseguito" style="display:none;margin-top:6px;">
      <div class="table-scroll">
        <table class="sets-table">
          <thead><tr><th></th><th>Kg</th><th>RIR</th><th>Reps</th></tr></thead>
          <tbody>${setsRows}</tbody>
        </table>
      </div>
      <label>Note esercizio</label>
      <textarea data-role="exnotes" placeholder="Note (opzionale)"></textarea>
    `;
    wrap.appendChild(card);

    const sel = card.querySelector('[data-role=exselect]');
    const custom = card.querySelector('[data-role=excustom]');
    sel.addEventListener('change', ()=>{
      custom.style.display = sel.value==='__custom__' ? 'block' : 'none';
    });
  });

  document.getElementById('wo-session-fields').style.display='block';
  document.getElementById('wo-hiit').value = prog.hiit? 'si':'no';
}

function escapeHtml(s){
  return String(s).replace(/[&<>"']/g, c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}

document.getElementById('wo-pain').addEventListener('input', e=>{
  document.getElementById('wo-pain-out').textContent = e.target.value;
});
document.getElementById('wo-energy').addEventListener('input', e=>{
  document.getElementById('wo-energy-out').textContent = e.target.value;
});

document.getElementById('btn-save-workout').addEventListener('click', ()=>{
  if(!currentWO){ showToast('Seleziona un workout'); return; }
  const date = document.getElementById('wo-date').value || todayISO();
  const cards = document.querySelectorAll('#wo-exercises .ex-card');
  const exercises = [];
  let anyData=false;
  cards.forEach(card=>{
    const exId = card.dataset.exid;
    const progEx = PROGRAM[currentWO].exercises.find(e=>e.id===exId);
    const sel = card.querySelector('[data-role=exselect]');
    const custom = card.querySelector('[data-role=excustom]');
    let executedName = sel.value;
    if(executedName==='__custom__'){
      executedName = custom.value.trim() || progEx.name;
    }
    const sets=[];
    for(let i=1;i<=NUM_SETS_UI;i++){
      const kg = num(card.querySelector(`[data-role=kg][data-set="${i}"]`).value);
      const rir = num(card.querySelector(`[data-role=rir][data-set="${i}"]`).value);
      const reps = num(card.querySelector(`[data-role=reps][data-set="${i}"]`).value);
      if(kg!=null||rir!=null||reps!=null) anyData=true;
      sets.push({kg,rir,reps});
    }
    const exnotes = card.querySelector('[data-role=exnotes]').value.trim();
    exercises.push({
      exId, plannedName: progEx.name, executedName,
      substituted: executedName!==progEx.name,
      pullupType: progEx.pullup || null,
      sets, notes: exnotes
    });
  });

  if(!anyData){ showToast('Registra almeno un dato di un esercizio'); return; }

  const workout = {
    id: uid(),
    date,
    type: currentWO,
    duration: num(document.getElementById('wo-duration').value),
    hiit: document.getElementById('wo-hiit').value,
    pain: parseInt(document.getElementById('wo-pain').value,10),
    energy: parseInt(document.getElementById('wo-energy').value,10),
    notes: document.getElementById('wo-notes').value.trim(),
    exercises
  };
  DATA.workouts.push(workout);
  saveData();
  showToast('Workout salvato');

  // reset form
  document.getElementById('wo-duration').value='';
  document.getElementById('wo-notes').value='';
  document.getElementById('wo-pain').value=0; document.getElementById('wo-pain-out').textContent='0';
  document.getElementById('wo-energy').value=5; document.getElementById('wo-energy-out').textContent='5';
  document.querySelectorAll('.wo-pick-btn').forEach(b=>b.classList.remove('active'));
  document.getElementById('wo-exercises').innerHTML='';
  document.getElementById('wo-session-fields').style.display='none';
  currentWO=null;
  document.getElementById('wo-date').value = todayISO();
});

/* ===================== PROGRESS ===================== */
function drawLineChart(canvasId, points, opts){
  opts = opts||{};
  const canvas = document.getElementById(canvasId);
  const dpr = window.devicePixelRatio||1;
  const rect = canvas.getBoundingClientRect();
  const w = Math.max(rect.width, canvas.parentElement.clientWidth-28) || 300;
  const h = 180;
  canvas.width = w*dpr; canvas.height = h*dpr;
  canvas.style.width='100%'; canvas.style.height=h+'px';
  const ctx = canvas.getContext('2d');
  ctx.scale(dpr,dpr);
  ctx.clearRect(0,0,w,h);

  if(!points || points.length===0){
    ctx.fillStyle = getCss('--text-dim');
    ctx.font='12px -apple-system,sans-serif';
    ctx.textAlign='center';
    ctx.fillText('Nessun dato ancora disponibile', w/2, h/2);
    return;
  }

  const padL=38, padR=10, padT=14, padB=22;
  const plotW = w-padL-padR, plotH = h-padT-padB;
  const values = points.map(p=>p.y);
  let minV = Math.min(...values), maxV = Math.max(...values);
  if(minV===maxV){ minV -= 1; maxV += 1; }
  const pad10 = (maxV-minV)*0.12;
  minV -= pad10; maxV += pad10;

  // gridlines
  ctx.strokeStyle = getCss('--border');
  ctx.lineWidth=1;
  const gridN=4;
  ctx.fillStyle = getCss('--text-dim');
  ctx.font='10px -apple-system,sans-serif';
  ctx.textAlign='right';
  for(let i=0;i<=gridN;i++){
    const y = padT + (plotH*i/gridN);
    ctx.beginPath(); ctx.moveTo(padL,y); ctx.lineTo(w-padR,y); ctx.stroke();
    const val = maxV - (maxV-minV)*i/gridN;
    ctx.fillText(val.toFixed(opts.decimals!=null?opts.decimals:0), padL-6, y+3);
  }

  function xFor(i){ return padL + (points.length===1? plotW/2 : plotW*i/(points.length-1)); }
  function yFor(v){ return padT + plotH - ((v-minV)/(maxV-minV))*plotH; }

  // line
  ctx.strokeStyle = getCss('--accent');
  ctx.lineWidth=2.2;
  ctx.beginPath();
  points.forEach((p,i)=>{
    const x=xFor(i), y=yFor(p.y);
    if(i===0) ctx.moveTo(x,y); else ctx.lineTo(x,y);
  });
  ctx.stroke();

  // area fill
  const grad = ctx.createLinearGradient(0,padT,0,padT+plotH);
  grad.addColorStop(0,'rgba(198,255,60,.22)');
  grad.addColorStop(1,'rgba(198,255,60,0)');
  ctx.fillStyle=grad;
  ctx.beginPath();
  points.forEach((p,i)=>{
    const x=xFor(i), y=yFor(p.y);
    if(i===0) ctx.moveTo(x,y); else ctx.lineTo(x,y);
  });
  ctx.lineTo(xFor(points.length-1), padT+plotH);
  ctx.lineTo(xFor(0), padT+plotH);
  ctx.closePath(); ctx.fill();

  // points
  ctx.fillStyle = getCss('--accent');
  points.forEach((p,i)=>{
    ctx.beginPath();
    ctx.arc(xFor(i), yFor(p.y), 2.6, 0, Math.PI*2);
    ctx.fill();
  });

  // x labels (first, mid, last)
  ctx.fillStyle = getCss('--text-dim');
  ctx.font='9.5px -apple-system,sans-serif';
  ctx.textAlign='center';
  const idxs = points.length<=6 ? points.map((_,i)=>i) : [0, Math.floor((points.length-1)/2), points.length-1];
  idxs.forEach(i=>{
    ctx.fillText(points[i].label, xFor(i), h-6);
  });
}
function getCss(varName){
  return getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
}

function renderProgress(){
  const sortedCI = [...DATA.checkins].filter(c=>c.weight!=null).sort((a,b)=>a.date.localeCompare(b.date));
  drawLineChart('chart-weight', sortedCI.map(c=>({y:c.weight,label:fmtDate(c.date).slice(0,5)})), {decimals:1});

  const sortedCIW = [...DATA.checkins].filter(c=>c.waist!=null).sort((a,b)=>a.date.localeCompare(b.date));
  drawLineChart('chart-waist', sortedCIW.map(c=>({y:c.waist,label:fmtDate(c.date).slice(0,5)})), {decimals:1});

  // pull-up max per session (free)
  const puPoints=[];
  [...DATA.workouts].sort((a,b)=>a.date.localeCompare(b.date)).forEach(w=>{
    w.exercises.forEach(ex=>{
      if(ex.pullupType==='free'){
        const maxReps = Math.max(0, ...ex.sets.filter(s=>s.reps!=null).map(s=>s.reps));
        if(maxReps>0) puPoints.push({y:maxReps, label:fmtDate(w.date).slice(0,5)});
      }
    });
  });
  drawLineChart('chart-pullup', puPoints, {decimals:0});

  const volPoints = [...DATA.workouts].sort((a,b)=>a.date.localeCompare(b.date)).map(w=>({y:sessionVolume(w), label:fmtDate(w.date).slice(0,5)}));
  drawLineChart('chart-volume', volPoints, {decimals:0});

  // best loads table
  const bestByName = {};
  DATA.workouts.forEach(w=>{
    w.exercises.forEach(ex=>{
      ex.sets.forEach(s=>{
        if(s.kg!=null){
          const key = ex.executedName;
          if(!bestByName[key] || s.kg>bestByName[key].kg){
            bestByName[key] = {kg:s.kg, date:w.date};
          }
        }
      });
    });
  });
  const tbody = document.querySelector('#tbl-loads tbody');
  tbody.innerHTML='';
  const names = Object.keys(bestByName).sort();
  if(!names.length){
    tbody.innerHTML = `<tr><td colspan="3" style="color:var(--text-dim);">Nessun dato ancora</td></tr>`;
  } else {
    names.forEach(n=>{
      const row = document.createElement('tr');
      row.innerHTML = `<td>${escapeHtml(n)}</td><td class="num">${bestByName[n].kg} kg</td><td>${fmtDate(bestByName[n].date)}</td>`;
      tbody.appendChild(row);
    });
  }

  // weeks bars
  const wb = document.getElementById('week-bars');
  wb.innerHTML='';
  const wc = weeksCount();
  const maxC = Math.max(3, ...wc);
  wc.forEach((c,i)=>{
    const col = document.createElement('div');
    col.className='week-bar-col';
    const h = Math.max(2, (c/maxC)*100);
    col.innerHTML = `<div style="font-size:10px;color:var(--text-dim);">${c}</div><div class="week-bar" style="height:${h}%;"></div><div class="week-bar-lbl">S${i+1}</div>`;
    wb.appendChild(col);
  });
}

/* ===================== HISTORY ===================== */
function renderHistory(){
  const tbody = document.querySelector('#tbl-history tbody');
  tbody.innerHTML='';
  const sorted = [...DATA.workouts].sort((a,b)=>b.date.localeCompare(a.date));
  document.getElementById('history-empty').style.display = sorted.length? 'none':'block';
  sorted.forEach(w=>{
    const vol = Math.round(sessionVolume(w));
    const painColor = w.pain>=7?'var(--red)':(w.pain>=4?'#e0c840':'var(--accent2)');
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td>${fmtDate(w.date)}</td>
      <td>${w.type}</td>
      <td class="num">${w.duration!=null? w.duration+"'":'—'}</td>
      <td class="num">${vol} kg</td>
      <td>${w.hiit==='si'?'✔':'—'}</td>
      <td><span class="pain-badge" style="background:${painColor}22;color:${painColor};">${w.pain!=null?w.pain:'—'}</span></td>
      <td style="max-width:160px;white-space:normal;">${escapeHtml(w.notes||'')}</td>
      <td><button class="del-btn" data-id="${w.id}" data-type="workout">✕</button></td>
    `;
    tbody.appendChild(tr);
  });

  const tbody2 = document.querySelector('#tbl-checkins tbody');
  tbody2.innerHTML='';
  const sortedCI = [...DATA.checkins].sort((a,b)=>b.date.localeCompare(a.date));
  document.getElementById('checkins-empty').style.display = sortedCI.length? 'none':'block';
  sortedCI.forEach(c=>{
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td>${fmtDate(c.date)}</td>
      <td class="num">${c.weight!=null? c.weight+' kg':'—'}</td>
      <td class="num">${c.waist!=null? c.waist+' cm':'—'}</td>
      <td class="num">${c.sleep!=null? c.sleep+'h':'—'}</td>
      <td class="num">${c.energy!=null? c.energy:'—'}</td>
      <td><button class="del-btn" data-id="${c.id}" data-type="checkin">✕</button></td>
    `;
    tbody2.appendChild(tr);
  });

  document.querySelectorAll('.del-btn').forEach(btn=>{
    btn.addEventListener('click', ()=>{
      const id = btn.dataset.id, type = btn.dataset.type;
      if(type==='workout') DATA.workouts = DATA.workouts.filter(w=>w.id!==id);
      else DATA.checkins = DATA.checkins.filter(c=>c.id!==id);
      saveData();
      renderHistory();
      renderCockpit();
    });
  });
}

/* ===================== SETTINGS ===================== */
document.getElementById('set-startdate').value = DATA.settings.startDate || '';
document.getElementById('btn-save-startdate').addEventListener('click', ()=>{
  const v = document.getElementById('set-startdate').value;
  if(!v){ showToast('Seleziona una data'); return; }
  DATA.settings.startDate = v;
  saveData();
  showToast('Data inizio salvata');
  renderCockpit();
});

document.getElementById('btn-export-json').addEventListener('click', ()=>{
  const blob = new Blob([JSON.stringify(DATA,null,2)], {type:'application/json'});
  downloadBlob(blob, 'SPARTA_PROJECT_backup.json');
  showToast('Backup JSON esportato');
});

document.getElementById('input-import-json').addEventListener('change', (e)=>{
  const file = e.target.files[0];
  if(!file) return;
  const reader = new FileReader();
  reader.onload = ()=>{
    try{
      const parsed = JSON.parse(reader.result);
      if(!parsed.workouts || !parsed.checkins || !parsed.settings){
        throw new Error('formato non valido');
      }
      DATA = parsed;
      saveData();
      showToast('Dati importati con successo');
      document.getElementById('set-startdate').value = DATA.settings.startDate || '';
      renderCockpit(); renderProgress(); renderHistory();
    }catch(err){
      console.error(err);
      showToast('File JSON non valido');
    }
  };
  reader.readAsText(file);
  e.target.value='';
});

document.getElementById('btn-export-csv').addEventListener('click', ()=>{
  const rows = [];
  rows.push(['tipo','data','workout','esercizio_programmato','esercizio_eseguito','kg','rir','reps_set1','reps_set2','reps_set3','reps_set4','durata_min','hiit','dolore','energia','note']);
  DATA.workouts.forEach(w=>{
    if(!w.exercises.length){
      rows.push(['workout', w.date, w.type, '','','','','','','','', w.duration??'', w.hiit??'', w.pain??'', w.energy??'', w.notes||'']);
    }
    w.exercises.forEach(ex=>{
      const kg = ex.sets.find(s=>s.kg!=null)?.kg ?? '';
      const rir = ex.sets.find(s=>s.rir!=null)?.rir ?? '';
      const r = [1,2,3,4].map(i=> ex.sets[i-1] && ex.sets[i-1].reps!=null ? ex.sets[i-1].reps : '');
      rows.push(['workout', w.date, w.type, ex.plannedName, ex.executedName, kg, rir, r[0],r[1],r[2],r[3], w.duration??'', w.hiit??'', w.pain??'', w.energy??'', (ex.notes||w.notes||'')]);
    });
  });
  DATA.checkins.forEach(c=>{
    rows.push(['checkin', c.date, '', '', '', '', '', '', '', '', '', '', '', '', c.energy??'', `peso:${c.weight??''} vita:${c.waist??''} sonno:${c.sleep??''}`]);
  });
  const csv = rows.map(r=> r.map(csvEscape).join(',')).join('\r\n');
  const blob = new Blob(['\ufeff'+csv], {type:'text/csv;charset=utf-8;'});
  downloadBlob(blob, 'SPARTA_PROJECT_export.csv');
  showToast('CSV esportato');
});
function csvEscape(v){
  const s = String(v==null?'':v);
  if(/[",\n;]/.test(s)) return '"'+s.replace(/"/g,'""')+'"';
  return s;
}
function downloadBlob(blob, filename){
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href=url; a.download=filename;
  document.body.appendChild(a); a.click(); document.body.removeChild(a);
  setTimeout(()=>URL.revokeObjectURL(url), 2000);
}

document.getElementById('btn-reset').addEventListener('click', ()=>{
  document.getElementById('reset-modal').classList.add('active');
});
document.getElementById('reset-cancel').addEventListener('click', ()=>{
  document.getElementById('reset-modal').classList.remove('active');
});
document.getElementById('reset-confirm').addEventListener('click', ()=>{
  DATA = defaultData();
  saveData();
  document.getElementById('set-startdate').value='';
  document.getElementById('reset-modal').classList.remove('active');
  showToast('Tutti i dati sono stati cancellati');
  renderCockpit(); renderProgress(); renderHistory();
});

/* ===================== INIT ===================== */
window.addEventListener('resize', ()=>{
  if(document.getElementById('panel-progress').classList.contains('active')) renderProgress();
});

renderCockpit();
renderHistory();

})();
</script>
</body>
</html>